// Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::path::Path;

use maestro_derive::MsgTag;
use ohmw_derive::{BorrowDecode, Decode, Encode};

#[derive(BorrowDecode)]
pub struct CreateProjectReq<'a> {
    pub workspace_path: &'a str,
    pub project_name: &'a str,
    pub project_detail: &'a str,
}

#[derive(Encode, Decode, MsgTag)]
#[msg_tag(case = "snake_case")]
pub struct CreateProjectRet {
    pub success: bool,
    pub message: String,
}

pub async fn create_project(req: CreateProjectReq<'_>) -> CreateProjectRet {
    let project_path = Path::new(req.workspace_path).join(req.project_name);
    if project_path.exists() {
        return CreateProjectRet {
            success: false,
            message: format!("project {} already exists", req.project_name),
        };
    }

    if let Err(e) = tokio::fs::create_dir(&project_path).await {
        return CreateProjectRet {
            success: false,
            message: format!("failed to create project directory: {}", e),
        };
    }

    let project_config_path = project_path.join("maestro_project.json");
    if let Err(e) = tokio::fs::write(&project_config_path, req.project_detail).await {
        return CreateProjectRet {
            success: false,
            message: format!("failed to write project config: {}", e),
        };
    }

    CreateProjectRet {
        success: true,
        message: project_path.to_string_lossy().to_string(),
    }
}
